<?php
ob_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $remember_me = $_POST['remember'];
    include('db/conn.php');
    $sql = "select * from teacher where t_id='$username' and password='$password'";
    $result = mysqli_query($cn, $sql);
    if (mysqli_num_rows($result) > 0) {
        $real_name = mysqli_fetch_array($result)[1];
        if (!empty($remember_me)) {
            setcookie('username', $username, time() + 3600 * 24 * 7);
            setcookie('password', $password, time() + 3600 * 24 * 7);
        } else {
            setcookie('username', $username, time() - 3600);
            setcookie('password', $password, time() - 3600);
        }
        session_start();
        $_SESSION['username'] = $username;
        $_SESSION['password'] = $password;
        echo "<script>location.href='manage.php';</script>";
    } else {
        session_unset();
        session_destroy();
        setcookie('username', $username, time() - 3600);
        setcookie('password', $password, time() - 3600);
        echo "<script>alert('工号或密码错误！');history.go(-1);</script>";
    }
} else {
    if (!empty($_COOKIE['username']) && !empty($_COOKIE['password'])) {
        $username = $_COOKIE['username'];
        $password = $_COOKIE['password'];
        include('db/conn.php');
        $sql = "select * from teacher where t_id='$username' and password='$password'";
        $result = mysqli_query($cn, $sql);
        if (mysqli_num_rows($result) > 0) {
            $real_name = mysqli_fetch_array($result)[1];
            session_start();
            $_SESSION['username'] = $username;
            $_SESSION['password'] = $password;
            echo "<script>location.href='manage.php';</script>";
        } else {
            session_unset();
            session_destroy();
            setcookie('username', $username, time() - 3600);
            setcookie('password', $password, time() - 3600);
            echo "<script>location.href='login.php';</script>";
        }
    } else {
        echo "<script>location.href='login.php';</script>";
    }
}
ob_end_flush();